package com.jiao.service.impl;

import com.jiao.domain.DTO.UserDto;
import com.jiao.domain.LoginUser;
import com.jiao.domain.Result;
import com.jiao.domain.VO.BlogUserLoginVo;
import com.jiao.domain.VO.UserInfoVo;
import com.jiao.enums.ExceptionCodeEnum;
import com.jiao.service.BlogLoginService;
import com.jiao.utils.BeanCopyUtils;
import com.jiao.utils.JwtUtil;
import com.jiao.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class BlogLoginServiceImpl implements BlogLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public Result<BlogUserLoginVo> login(UserDto userDto) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDto.getUserName(), userDto.getPassword());
        //对于Authentication对象的操作api都封装在AuthenticationManager对象中。authenticate方法会调用loadUserByUsername方法
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断是否认证通过
        if(Objects.isNull(authenticate)){
            throw new RuntimeException(ExceptionCodeEnum.LOGIN_ERROR.getMsg());
        }
        //获取userid 生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getSysUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //把用户信息存入redis
        redisCache.setCacheObject("blogLogin:"+userId,loginUser);

        //把token和userinfo封装 返回
        //把SysUser数据库信息转换成UserInfoVo
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getSysUser(), UserInfoVo.class);
        BlogUserLoginVo vo = new BlogUserLoginVo(jwt,userInfoVo);
        return Result.success(vo);
    }

    @Override
    public Result<String> logout() {
        //获取token 解析获取userid
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //获取userid
        Long userId = loginUser.getSysUser().getId();
        //删除redis中的用户信息
        redisCache.deleteObject("blogLogin:"+userId);
        return Result.success();
    }
}